<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon></el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="cat-opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联选择框 -->
                    <!-- 级联选择器 -->
                    <el-cascader clearable expand-trigger="hover" v-model="selectKeyid" :options="CateList"
                        :props="catesProps" @change="cateshandleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数的按钮 -->
                    <el-button type="primary" :disabled="isbtn" @click="adddialogVisible=true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableList" border stripe>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(i,scope.row)">{{item}}</el-tag>
                                <!-- 文本输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- tag按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit"
                                    @click="editshowDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete"
                                    @click="deleteEdit(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <!-- 添加属性的按钮 -->
                    <el-button type="primary" :disabled="isbtn" @click="adddialogVisible=true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableList" border stripe>
                          <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="deleteTag(i,scope.row)">{{item}}</el-tag>
                                <!-- 文本输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- tag按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit"
                                    @click="editshowDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete"
                                    @click="deleteEdit(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加动态参数以及静态属性的对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="adddialogVisible" width="70%" @close="closeAddDialog">
            <el-form :model="addruleForm" :rules="addrules" ref="ruleFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addruleForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="adddialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改动态参数以及静态属性的对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editdialogVisible" width="70%" @close="closeEditDialog">
            <el-form :model="editRuleForm" :rules="editRules" ref="editRuleFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editRuleForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                //存放商品分类的列表数据数组
                CateList: [],
                //存放级联选择器选中项的id
                selectKeyid: [],
                //级联选择器的配置对象
                catesProps: {
                    //选中的值id
                    value: 'cat_id',
                    // 看到的值
                    label: 'cat_name',
                    //父子节点嵌套关系
                    children: 'children'
                },
                // tabs标签双向数据绑定的值
                activeName: 'many',
                //存放动态参数的数据
                manyTableList: [],
                //存放静态属性的数据
                onlyTableList: [],
                //控制添加动态参数，以及静态属性对话框的显示与隐藏
                adddialogVisible: false,
                //添加参数的表单对象
                addruleForm: {
                    attr_name: ''

                },
                //添加参数的验证规则对象
                addrules: {
                    attr_name: [{
                        required: true,
                        message: '请输入参数名称',
                        trigger: 'blur'
                    }, ]
                },
                //控制修改对话框的显示与隐藏
                editdialogVisible: false,
                //修改表单的数据对象
                editRuleForm: {
                    attr_name: '',

                },
                //修改表单的验证规则对象
                editRules: {
                    attr_name: [{
                        required: true,
                        message: '请输入参数名称',
                        trigger: 'blur'
                    }, ]
                },




            }
        },
        created() {
            this.getCatesList();
        },
        methods: {
            //获取参数列表数据
            async getCatesList() {
                const {
                    data: res
                } = await this.$http.get('categories', {
                    params: {
                        type: 3
                    }
                });
                console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error('获取商品分类列表数据失败')
                }
                this.CateList = res.data;
            },
            //级联选择器选中项的值发生变化触发的事件
            cateshandleChange() {
                this.getParamsData();

            },
            //页签切换触发的事件
            handleClick() {
                this.getParamsData();
                console.log(this.activeName);
            },
            //获取参数的列表数据
            async getParamsData() {
                //只允许选择三级分类
                if (this.selectKeyid.length !== 3) {
                    this.selectKeyid = [];
                    this.manyTableList=[];
                    this.onlyTableList=[];
                    return;
                }
                //发起获取动态参数和静态属性的请求
                const {
                    data: res
                } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                    params: {
                        sel: this.activeName
                    }
                });
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数列表失败')
                }
                console.log(res.data, "111");
                //将res.data中的字符串attr_vals转换为数组，最后采用for循环添加el-tag标签中
                res.data.forEach(item => {
                    //判断循环的每一个item项是否为空字符串，如果为空字符串就转化为空数组
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                    //为每一项重新定义一个inputVisiable布尔值，默认为false
                    item.inputVisible = false;
                    //为每一项重新定义一个存放文本输入框中数据的值，默认为空
                    item.inputValue = '';
                })
                console.log(res.data, "数组");
                //判断获取的数据时动态参数的数据还是静态属性的数据
                if (this.activeName == 'many') {
                    this.manyTableList = res.data;
                } else {
                    this.onlyTableList = res.data;
                }
            },
            //监听添加动态参数，以及静态属性对话框的关闭事件，清空表单
            closeAddDialog() {
                this.$refs.ruleFormRef.resetFields();
            },
            //点击添加参数对话框的确定按钮，发起添加参数的请求
            addParams() {
                //发起请求前进行预验证
                this.$refs.ruleFormRef.validate(async valid => {
                    if (!valid) return;
                    const {
                        data: res
                    } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                        attr_name: this.addruleForm.attr_name,
                        attr_sel: this.activeName,
                    })
                    console.log(res, "222");
                    if (res.meta.status !== 201) {
                        this.$message.error('添加参数失败')
                    }
                    this.$message.success('添加参数成功');
                    this.adddialogVisible = false;
                    this.getCatesList();
                })
            },
            //修改对话框的关闭触发的事件
            closeEditDialog() {
                this.$refs.editRuleFormRef.resetFields();

            },
            //点击编辑按钮触发的函数
            async editshowDialog(attr_id) {
                const {
                    data: res
                } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
                    params: {
                        attr_sel: this.activeName
                    }
                })
                console.log(res, "123");
                if (res.meta.status !== 200) {
                    this.$message.error('获取参数信息失败')
                }
                this.editRuleForm = res.data;
                this.editdialogVisible = true
            },
            //点击编辑编辑按钮弹出对话框，点击确定触发的事件
            editParams() {
                //进行编辑提交修改后的参数前进行预验证
                this.$refs.editRuleFormRef.validate(async valid => {
                    if (!valid) return;
                    //发起编辑提交的请求
                    const {
                        data: res
                    } = await this.$http.put(
                        `categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`, {
                            attr_name: this.editRuleForm.attr_name,
                            attr_sel: this.activeName,
                        });
                    console.log(res);
                    if (res.meta.status !== 200) {
                        this.$message.error('更新参数失败');
                    }
                    this.$message.success('更新参数成功');
                    this.editdialogVisible = false;
                    this.getCatesList();
                })

            },
            //点击删除按钮触发的函数
            async deleteEdit(attr_id) {
                const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => {
                    return error;
                });
                console.log(result);
                if (result !== 'confirm') {
                   return  this.$message.info('用户取消了删除操作')
                }
                const {
                    data: res
                } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`);
                console.log(res, "222");
                if (res.meta.status !== 200) {
                    this.$message.error('删除参数失败')
                }
                this.$message.success('删除参数成功');
                this.getCatesList();

            },
            //文本输入框中按下enter建以及失去焦点时触发的事件
             handleInputConfirm(row) {
                //文本输入框失去焦点以及按下enter之后先判断用户是否输入了合法的字符，如果不是就清空
                if(row.inputValue.trim().length===0){
                    row.inputValue='',
                    row.inputVisible=false;
                    return
                }else{
                    //用户输入了合法的字符,就push到tag标签数组中
                    row.attr_vals.push(row.inputValue.trim());
                    //push之后在清空文本本输入框
                    row.inputValue='';
                    row.inputVisible=false;
                    //需要发起请求，保存这一次的操作
                    // const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                    //     attr_name:row.attr_name,
                    //     attr_sel:row.attr_sel,
                    //     //将attr_vals数组拼接成字符串，用空格隔开
                    //     attr_vals:row.attr_vals.join(' ')
                    // });
                    // console.log(res);
                    // if(res.meta.status!==200){
                    //     return this.$message.error('添加参数项失败')
                    // }
                    // this.$message.success('添加参数项成功');
                    this.saveVales(row);


                }
                

            },
            //tag标签按钮点击时触发的事件
            showInput(row) {
                //展示文本输入框
                row.inputVisible = true;
                   //让文本输入框自动获取焦点
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            //保存删除tag标签的操作到数据库中
            async saveVales(row){
                     //需要发起请求，保存这一次的操作
                    const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                        attr_name:row.attr_name,
                        attr_sel:row.attr_sel,
                        //将attr_vals数组拼接成字符串，用空格隔开
                        attr_vals:row.attr_vals.join(' ')
                    });
                    console.log(res);
                    if(res.meta.status!==200){
                        return this.$message.error('修改参数项失败')
                    }
                    this.$message.success('修改参数项成功');
            },
            //删除tag标签触发的事件
            deleteTag(i,row){
                row.attr_vals.splice(i,1);
                this.saveVales(row)


            }


        },
        computed: {
            //控制添加参数和添加属性按钮的启用与禁用,返回布尔值
            //true为禁用，false为启用
            isbtn() {
                if (this.selectKeyid.length !== 3) {
                    return true;
                }
                return false;
            },
            //当前选中的三级分类的id
            cateId() {
                if (this.selectKeyid.length !== 3) {
                    return null;
                } else {
                    return this.selectKeyid[2]
                }
            },
            //动态参数，静态属性的标题文本计算属性
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数'
                } else {
                    return '静态属性'
                }
            }
        }
    }
</script>
<style lang="less" scoped>
    .cat-opt {
        margin: 15px 0;
    }

    .el-tag {
        margin: 10px;
    }

    .input-new-tag {
        width: 120px;
    }
</style>